import { HttpError, toSuccess, useEntityManager } from "@sker/core";
import { AutoUser, KsLiveRoomDayLog } from "@sker/entities";
import { useData } from "@sker/runtime";
import { z } from "zod";

export default async () => {
    const input = z.object({
        token: z.string()
    });
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const user = await m.findOne(AutoUser, { where: { token: body.token } })
        if (!user) throw new HttpError(`参数错误`)
        if(user.replace_mobile) user.mobile = user.replace_mobile
        const date = new Date()
        const year = date.getFullYear()
        const month = date.getMonth() + 1;
        const list = await m.createQueryBuilder()
            .select('sum(log.count)', 'count')
            .addSelect('log.day', 'day')
            .addSelect('log.pkg', 'pkg')
            .addSelect('count(1)', 'device_count')
            .addSelect('max(log.count)', 'max_count')
            .from(KsLiveRoomDayLog, 'log')
            .where('log.year=:year', { year: `${year}` })
            .andWhere('log.month=:month', { month: `${month}` })
            .andWhere('log.owner=:owner', { owner: user.mobile })
            .groupBy('log.day')
            .addGroupBy('log.pkg')
            .orderBy(`log.day`, 'ASC')
            .execute()
        const dataList = list.map(li=>{
            li.day = parseInt(li.day)
            return li;
        })
        return toSuccess(dataList)
    })
}
